<template>
  <div class="staycookies_wrapper">
    <div class="staycookies-btn_wrapper">
      <el-button type="primary" :loading="freezeLoading" @click="freezeCurrentCookie">冻结</el-button>
      <el-button type="danger" :loading="unfreezeLoading" @click="unfreezeCurrentCookie">解冻</el-button>
    </div>
    <div class="staycookies-list_wrapper">
      <el-table
        :data="tableList"
        style="width: 100%">
        <el-table-column
          prop="host"
          label="域名">
        </el-table-column>
        <el-table-column
          prop="cookie"
          label="cookie">
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
const LOCALSTORAGE_COOKIES_KEY = 'TOOLS_FREEZE_COOKIESLIST'
export default {
  name: 'StayCookies',
  data() {
    return {
      freezeLoading: false,
      unfreezeLoading: false,
      tableList: []
    }
  },
  async mounted() {
    // 从页面localStorage中获取 冻结列表数据
    const res = await this.getFreezeData(LOCALSTORAGE_COOKIES_KEY)
    if (res) {
      this.tableList = JSON.parse(res)
    }
  },
  methods: {
    async freezeCurrentCookie() {
      const _self = this
      let bool = true
      this.freezeLoading = true
      // 获取 host cookie
      const info = await this.getCurrentHostCookie()
      const tableList = JSON.parse(JSON.stringify(this.tableList))
      if (info) {
        const { host, cookie } = info
        const itemIndex = tableList.findIndex(i => i.host === host)
        if (itemIndex !== -1) {
          tableList[itemIndex].cookie = cookie
        } else {
          tableList.unshift({
            host, cookie
          })
        }
        // 更新、新增 到冻结列表中
        this.tableList = tableList
        const res = await this.setFreezeData(LOCALSTORAGE_COOKIES_KEY, JSON.stringify(tableList))
        if (res) {
          _self.$message({
            message: '冻结成功',
            type: 'success'
          })
        } else {
          bool = false
        }
      } else {
        bool = false
      }
      if (!bool) {
        this.$message({
          message: '抱歉，操作失败，请重试',
          type: 'warning'
        })
      }
      // 将冻结列表保存到 页面的 localStorage
      this.freezeLoading = false
    },
    async unfreezeCurrentCookie() {
      const _self = this
      let bool = true
      this.unfreezeLoading = true
      // 获取 host
      const info = await this.getCurrentHostCookie()
      const tableList = JSON.parse(JSON.stringify(this.tableList))
      if (info) {
        const { host } = info
        const itemIndex = tableList.findIndex(i => i.host === host)
        if (itemIndex !== -1) {
          tableList.splice(itemIndex, 1)
        }
        // 更新、新增 到冻结列表中
        this.tableList = tableList
        const res = await this.setFreezeData(LOCALSTORAGE_COOKIES_KEY, JSON.stringify(tableList))
        if (res) {
          _self.$message({
            message: '解冻成功',
            type: 'success'
          })
        } else {
          bool = false
        }
      } else {
        bool = false
      }
      if (!bool) {
        this.$message({
          message: '抱歉，操作失败，请重试',
          type: 'warning'
        })
      }
      // 将冻结列表保存到 页面的 localStorage
      this.unfreezeLoading = false
    },
    getCurrentHostCookie() {
      return new Promise((resolve) => {
        try {
          if (window.chrome && window.chrome.tabs) {
            window.chrome.tabs.query({
              active: true,
              currentWindow: true
            }, function (tabs) {
              let tabId = tabs.length ? tabs[0].id : null
              window.chrome.tabs.sendMessage(tabId, {
                message: 'GET_HOSTCOOKIE',
              }, function (response) {
                resolve(response)
              })
            })
          } else {
            resolve(false)
          }
        } catch {
          resolve(false)
        }
      })
    },
    setFreezeData(key, value) {
      return new Promise((resolve) => {
        try {
          if (window.chrome && window.chrome.tabs) {
            window.chrome.tabs.query({
              active: true,
              currentWindow: true
            }, function (tabs) {
              let tabId = tabs.length ? tabs[0].id : null
              window.chrome.tabs.sendMessage(tabId, {
                message: 'SET_FREEZEDATA',
                data: {
                  key,
                  value
                },
              }, function () {
                resolve(true)
              })
            })
          } else {
            resolve(false)
          }
        } catch {
          resolve(false)
        }
      })
    },
    getFreezeData(key) {
      return new Promise((resolve) => {
        try {
          if (window.chrome && window.chrome.tabs) {
            window.chrome.tabs.query({
              active: true,
              currentWindow: true
            }, function (tabs) {
              let tabId = tabs.length ? tabs[0].id : null
              window.chrome.tabs.sendMessage(tabId, {
                message: 'GET_FREEZEDATA',
                data: {
                  key,
                },
              }, function (response) {
                resolve(response)
              })
            })
          } else {
            resolve(false)
          }
        } catch {
          resolve(false)
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.staycookies_wrapper {
  width: 100%;
  height: 100%;
  padding: 30px;
  box-sizing: border-box;
  .staycookies-btn_wrapper {
    display: flex;
  }
}
</style>

